Type guards are conditions that allow you to narrow down the type of a variable within a certain scope. For example, using the `typeof` or `instanceof` operators. A type guard is a TypeScript technique used to get information about the type of a variable, usually within a conditional block. These are regular functions that return a boolean, taking a type and telling TypeScript if it can be narrowed down to something more specific. TypeScript uses some built-in JavaScript operators like typeof, instanceof, and the in operator, which is used to determine if an object contains a property.
There are five major ways to use a type guard:
- The instanceof keyword
- The typeof keyword
- The in keyword
- Equality narrowing type guard
- Custom type guard with predicate